package com.panshi.util;

import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.util.ResourceUtils;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Component
public class BaseUpload {
    private static String ak = "jo2e0wpf5ENsrDLBFObvFteDxa_cFtYvcA1BZqna";
    private static String sk = "Eve6T4-4RZVbUrzGt4SGaLFysQun0aSt-I_q-yax";   // 密钥配置
    private static Auth auth = Auth.create(ak, sk);    // TODO Auto-generated constructor stub
    private static String bucketname = "xhlmr";    //空间名
    String key = "";    //上传的图片名
    public String getUpToken() {
        return auth.uploadToken(bucketname, null, 3600, new StringMap().put("insertOnly", 1));
    }
    public void put64image() throws Exception {
        String file = "C:\\Users\\Administrator\\Desktop\\icon.png";//图片路径
        key = "abc";
        FileInputStream fis = null;
        int l = (int) (new File(file).length());
        byte[] src = new byte[l];
        fis = new FileInputStream(new File(file));
        fis.read(src);
        String file64 = Base64.encodeToString(src, 0);
        System.out.println(file64);
        String url = "http://up-z2.qiniup.com/putb64/" + l+"/key/"+ UrlSafeBase64.encodeToString(key);
        //非华东空间需要根据注意事项 1 修改上传域名
        RequestBody rb = RequestBody.create(null, file64);
        Request request = new Request.Builder().
                url(url).
                addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + getUpToken())
                .post(rb).build();
        System.out.println(request.headers());
        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        System.out.println(url);
    }

    public String [] decodingFile(String file64) throws IOException {
        // 通过base64来转化图片
        file64 = file64.split(",")[1];
        BASE64Decoder decoder = new BASE64Decoder();
        // Base64解码
        byte[] imageByte = null;
        try {
            imageByte = decoder.decodeBuffer(file64);
            for (int i = 0; i < imageByte.length; ++i) {
                if (imageByte[i] < 0) {// 调整异常数据
                    imageByte[i] += 256;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        UUID uuid = UUID.randomUUID();
        // 生成文件名

        String key = uuid.toString()+ System.currentTimeMillis()+".jpg";
        //项目的绝对路径
        String path = ResourceUtils.getURL("classpath:").getPath();
        // 生成文件路径
        String filePath =  path + key;
        File imageFile = new File(filePath);
        if(!imageFile.exists()){
            imageFile.createNewFile();
        }
        //因为BASE64Decoder的jar问题，此处使用spring框架提供的工具包
        byte[] bs = Base64Utils.decodeFromString(file64);
        //使用apache提供的工具类操作流
        FileUtils.writeByteArrayToFile(imageFile, bs);
        String [] strArr = new String[2];
        strArr[0] = key;
        strArr[1] = imageFile.getAbsolutePath();
        return strArr;
    }

    public String put64myImage(String file64) throws Exception {

        String arr [] = decodingFile(file64);

        String pathimage = arr[1];

        FileInputStream fis = null;
        int l = (int) (new File(pathimage).length());
        byte[] src = new byte[l];
        fis = new FileInputStream(new File(pathimage));
        fis.read(src);
        String filePath64 = Base64.encodeToString(src, 0);
        fis.close();
        String url = "http://up-z2.qiniup.com/putb64/"+l+"/key/"+UrlSafeBase64.encodeToString(arr[0]);

        //非华东空间需要根据注意事项 1 修改上传域名
        RequestBody rb = RequestBody.create(null, filePath64);
        Request request = new Request.Builder().
                url(url).
                addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken " + getUpToken())
                .post(rb).build();
        OkHttpClient client = new OkHttpClient();Response response = client.newCall(request).execute();
        new File(pathimage).delete();
        return "http://qiniu.xhlmr.cn/"+arr[0];
    }
}
